package collector.httpd.metad;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


import org.apache.log4j.Logger;
import org.eclipse.jetty.server.Request;
import org.eclipse.jetty.server.handler.AbstractHandler;

import collector.core.CollectConstants;
import collector.core.config.Config;
import collector.httpd.HttpdUtil;
import collector.httpd.metad.jobstate.JobStateHandler;
import collector.httpd.metad.logger.LogViewHandler;
import collector.httpd.metad.report.ReportHandler;
import collector.metaexec.MetaExec;


public class MetaHandler extends AbstractHandler {
	private Logger logger = Logger.getLogger(getClass());
	private Config config = Config.newInstance();
	private ReportHandler report = new ReportHandler();
	private JobStateHandler jobstate = new JobStateHandler();
	private LogViewHandler logview = new LogViewHandler();
	List<MetaExec> execList = null;

	public MetaHandler(List<MetaExec> execList) {
		this.execList = execList;
	}

	public void handle(String target, Request baseRequest
				, HttpServletRequest request, HttpServletResponse response)
				throws IOException, ServletException {
		if(!CollectConstants.URL_REPORT.equals(target)) {
			if(!HttpdUtil.checkAuth(baseRequest, response, config.getUsername(), config.getPassword())) {	// Login 처리
				logger.info("Auth failed.");
				return;
			}
		}

		HttpdUtil.addHeaderNoCache(response);

		try {
			if(CollectConstants.URL_REPORT.equals(target)) {	// 작업 상태 REPORT 요청 URL
				report.handle(target, baseRequest, request, response, execList);
			} else if(CollectConstants.URL_JOBSTATE.equals(target)) {	// 작업 상태 요청 URL
			    	jobstate.handle(target, baseRequest, request, response);
			} else if(CollectConstants.URL_LOGVIEW.equals(target)) {	// Log 획득 처리 요청 URL
			    	logview.handle(target, baseRequest, request, response);
//			} else if(CollectConstants.URL_GRAPH.equals(target)) {	// 작업 결과 그래프 요청 URL
//				graphHandler.handle(target, baseRequest, request, response);
//			} else if(CollectConstants.URL_LOGGER.equals(target)) {	// Log 획득 처리 요청 URL
//				LoggerAction loggerAction = new LoggerAction();
//				loggerAction.handle(target, baseRequest, request, response);
			} else {
				HttpdUtil.handleUnknown(target, baseRequest, request, response);
			}
		} catch (Exception e) {
			logger.warn(e.getMessage(), e);
		}
	}


}
